<template>
  <!-- 模板部分保持不变 -->
  <div class="wrapper">
    <div id="app">
      <!-- 导航栏 -->
      <nav class="nav-bar">
        <div class="nav-left">
          <router-link to="/" class="nav-link">首页</router-link>
          <router-link to="/contact" class="nav-link">购物车</router-link>
          <router-link to="/about" class="nav-link">我的订单</router-link>
          <router-link to="/user" class="nav-link">我的</router-link>
        </div>
        <div class="nav-right">
          <template v-if="isLoggedIn">
            <div class="user-info">
              <span>{{ userInfo.name || '用户' }}</span>
              <el-button type="text" @click="handleLogout">退出登录</el-button>
            </div>
          </template>
          <router-link to="/sign" class="nav-link" v-else>注册/登录</router-link>
        </div>
      </nav>

      <!-- 订单内容 -->
      <div class="content">
        <!-- 订单状态筛选 -->
        <div class="order-filter">
          <el-radio-group v-model="filterStatus" size="small" @change="handleFilterChange">
            <el-radio :label="0">全部订单</el-radio>
            <el-radio :label="2">待发货</el-radio>
            <el-radio :label="3">已发货</el-radio>
            <el-radio :label="4">已完成</el-radio>
            <!--<el-radio :label="5">申请退款</el-radio>
            <el-radio :label="6">已退款</el-radio>-->
          </el-radio-group>
        </div>

        <!-- 订单表格 -->
        <el-table 
          :data="filteredOrders" 
          style="width: 100%" 
          border 
          stripe
          v-loading="loading"
          element-loading-text="加载订单中..."
        >
          <el-table-column prop="orderId" label="订单编号" width="200" />
          <el-table-column prop="createTime" label="下单时间" width="180" />
          <el-table-column label="商品图片" width="120">
            <template #default="scope">
              <img 
                :src="getImageUrl(scope.row.goodsPic)"  
                alt="商品图片" 
                style="max-width:80px;max-height:80px;"
                @error="handleImageError($event)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="goodsName" label="商品名称" width="200" />
          <el-table-column prop="quantity" label="购买数量" width="120" />
          <el-table-column prop="unitPrice" label="单价" width="120" />
          <el-table-column prop="totalPrice" label="总价" width="120" class-name="text-red" />
          <el-table-column prop="orderStatus" label="订单状态" width="120">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.orderStatus)">{{ scope.row.orderStatus }}</el-tag>
            </template>
          </el-table-column>
          <!--<el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button 
                v-if="['待发货', '已发货', '已完成'].includes(scope.row.orderStatus)" 
                type="danger" 
                size="small" 
                @click="applyRefund(scope.row)"
              >
                申请退款
              </el-button>
            </template>
          </el-table-column>-->
        </el-table>

        <!-- 空状态提示 -->
        <div v-if="filteredOrders.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无订单数据" />
          <router-link to="/" class="nav-link" style="margin-top: 10px; display: inline-block;">
            去逛逛
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElMessageBox, ElEmpty, ElTag } from 'element-plus';

// 配置axios
axios.defaults.baseURL = 'http://127.0.0.1:8080';
axios.defaults.withCredentials = true;

// 添加请求拦截器（携带登录令牌）
axios.interceptors.request.use(config => {
  const userInfo = localStorage.getItem('userInfo');
  if (userInfo) {
    const { token } = JSON.parse(userInfo);
    if (token) {
      config.headers.Authorization = token;
    }
  }
  return config;
});

export default {
  name: 'AboutView',
  components: { ElEmpty, ElTag },
  data() {
    return {
      orderData: [],
      filterStatus: 0,
      loginUserId: null,
      isLoggedIn: false,
      userInfo: {},
      loading: false,
      errorMessage: ''
    }
  },
  computed: {
    filteredOrders() {
      if (this.filterStatus === 0) {
        return this.orderData;
      }
      const statusMap = {
        2: '待发货',
        3: '已发货',
        4: '已完成',
        5: '申请退款',
        6: '已退款'
      };
      const targetStatus = statusMap[this.filterStatus];
      return this.orderData.filter(item => item.orderStatus === targetStatus);
    }
  },
  mounted() {
    this.checkLoginStatus();
    if (this.isLoggedIn && this.loginUserId) {
      this.getOrderList();
    } else {
      this.$router.push('/sign').catch(err => {
        console.warn('跳转登录页失败:', err);
      });
      ElMessage.warning('请先登录查看订单');
    }
  },
  methods: {
    checkLoginStatus() {
      try {
        const storedUser = localStorage.getItem('userInfo');
        if (storedUser) {
          this.userInfo = JSON.parse(storedUser);
          this.isLoggedIn = true;
          this.loginUserId = this.userInfo.id;
        } else {
          this.clearUserInfo();
        }
      } catch (err) {
        console.error('解析用户信息失败:', err);
        this.clearUserInfo();
      }
    },

    handleLogout() {
      try {
        this.clearUserInfo();
        this.isLoggedIn = false;
        this.userInfo = {};
        this.loginUserId = null;
        ElMessage.success('已退出登录');
        this.$router.push('/').catch(err => {
          console.warn('路由跳转失败:', err);
        });
      } catch (err) {
        console.error('退出登录出错:', err);
        ElMessage.success('已退出登录');
      }
    },

    clearUserInfo() {
      try {
        localStorage.removeItem('userInfo');
        localStorage.removeItem('userId');
        this.isLoggedIn = false;
        this.loginUserId = null;
      } catch (err) {
        console.warn('清除本地存储失败:', err);
      }
    },

    async getOrderList() {
      this.loading = true;
      try {
        const res = await axios.get(`/orders/user/${this.loginUserId}`);
        
        if (!Array.isArray(res.data)) {
          throw new Error('订单数据格式错误，预期数组类型');
        }

        this.orderData = res.data.map(item => ({
          orderId: item.orderId || item.orderid || '',
          userId: item.userId || item.userid || 0,
          goodsId: item.goodsId || item.goodsid || 0,
          goodsName: item.goodsName || item.name || '未知商品',
          goodsPic: item.goodsPic || item.pic || '',
          quantity: item.quantity || 0,
          unitPrice: parseFloat(item.unitPrice || item.price) || 0,
          totalPrice: parseFloat(item.totalPrice || item.totalprice) || 0,
          orderStatus: item.orderStatus || item.orderstatus || '未知状态',
          createTime: this.formatDate(item.createTime || item.createtime),
          updateTime: this.formatDate(item.updateTime || item.updatetime)
        }));
      } catch (err) {
        const errorMsg = err.response?.data?.message 
          || err.response?.data 
          || err.message 
          || '获取订单失败，请稍后重试';
        ElMessage.error(`获取订单失败：${errorMsg}`);
        console.error('订单接口错误详情:', err);
        this.orderData = [];
      } finally {
        this.loading = false;
      }
    },

    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) {
        return '无效时间';
      }
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },

    getStatusType(statusText) {
      const typeMap = {
        '待发货': 'info',
        '已发货': 'primary',
        '已完成': 'success',
        '申请退款': 'danger',
        '已退款': 'error',
        '未知状态': 'default'
      };
      return typeMap[statusText] || 'default';
    },

    // 核心修改：申请退款方法
    async applyRefund(order) {
      if (!order.orderId) {
        ElMessage.warning('订单ID不存在，无法申请退款');
        return;
      }

      try {
        // 确认弹窗
        await ElMessageBox.confirm(
          `确定要对订单【${order.orderId}】申请退款吗？`,
          '申请退款',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        // 1. 构建请求参数（确保参数正确传递）
        const params = new URLSearchParams();
        params.append('orderId', order.orderId);
        params.append('orderStatus', '申请退款');

        // 2. 发送请求（使用正确的Content-Type和参数格式）
        const res = await axios.put(
          '/orders/status',
          params, // 用URLSearchParams传递参数，适配x-www-form-urlencoded
          {
            headers: {
              'Authorization': this.userInfo.token, // 明确携带token
              'Content-Type': 'application/x-www-form-urlencoded' // 强制指定Content-Type
            }
          }
        );

        // 3. 处理响应（兼容后端可能的不同返回格式）
        const successResponses = ['状态更新成功', '申请退款成功'];
        if (successResponses.includes(res.data) || res.data?.code === 200) {
          ElMessage.success('申请退款成功，订单状态已更新');
          this.getOrderList(); // 刷新订单列表
        } else {
          ElMessage.error(`退款失败：${res.data || '服务器处理失败'}`);
        }
      } catch (err) {
        // 忽略用户取消操作的错误
        if (err.name !== 'cancel') {
          // 详细错误信息展示，便于调试
          const errorDetails = {
            status: err.response?.status,
            data: err.response?.data,
            message: err.message
          };
          const errorMsg = err.response?.data?.message 
            || err.response?.data 
            || '申请退款失败，请检查网络或联系客服';
          ElMessage.error(`申请退款失败：${errorMsg}`);
          console.error('退款接口错误详情:', errorDetails);
        }
      }
    },

    getImageUrl(picName) {
      if (!picName) return '/default.png';
      return picName.startsWith('http') 
        ? picName 
        : `http://localhost:8080/images/${picName}`;
    },

    handleImageError(e) {
      e.target.src = '/default.png';
    },

    handleFilterChange() {
      console.log('筛选状态变更为:', this.filterStatus);
    }
  },
  watch: {
    loginUserId(newVal) {
      if (newVal) {
        this.getOrderList();
      }
    }
  }
};
</script>

<style scoped>
/* 样式部分保持不变 */
.wrapper {
  padding: 20px;
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.nav-left, .nav-right {
  display: flex;
  gap: 20px;
  align-items: center;
}

.nav-link {
  text-decoration: none;
  color: #333;
  padding: 5px 10px;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}

.nav-link.router-link-exact-active {
  color: #6b46c1;
  border-bottom-color: #6b46c1;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.content {
  padding-top: 20px;
}

.order-filter {
  margin-bottom: 20px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.el-table .cell img {
  border-radius: 4px;
  vertical-align: middle;
}

.text-red {
  color: #ff4d4f !important;
}

.empty-state {
  margin: 50px 0;
  text-align: center;
}
</style>